import React, { useState } from 'react';
import { useRequest } from 'ice';
import {
  Card,
  Table,
  Pagination,
  Divider,
  ResponsiveGrid,
  Button,
  Box,
  Form,
  Field,
  Input,
  Loading,
  Dialog,
  DatePicker,
  Message,
} from '@alifd/next';
import moment, { Moment } from 'moment';
import { DialogProps } from '@alifd/next/types/dialog';

import styles from './index.module.scss';

moment.locale('zh-cn');

const DialogScreen: React.FC<DialogProps & { cast: (args: object) => Promise<any> }> = (props) => {
  const { cast, ...lastProps } = props;
  const limit = 5;
  const [page, setPage] = useState(1);
  const [sort, setSort] = useState({
    field: 'createAt',
    order: 'desc',
  });
  const [filter, setFilter] = useState({});
  const field = Field.useField({ autoUnmount: false });
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [dateRange, setDateRange] = useState<Moment[]>();

  const { data, loading } = useRequest(
    () => ({
      url: '/api/screen',
      params: {
        limit,
        skip: (page - 1) * limit,
        ...filter,
        ...sort,
      },
    }),
    {
      manual: false,
      refreshDeps: [page, sort, filter],
    },
  );

  const onCast = (override: boolean) => {
    return () => {
      Dialog.confirm({
        title: '投放提醒',
        content: `确定要${override ? '覆盖' : '添加'}投放吗？`,
        onOk: async () => {
          try {
            await cast({
              screenIds: selectedIds,
              dateRange: dateRange?.map((v) => v.format('YYYY-MM-DD')),
              override,
            });
            Message.success('投放成功');
          } catch (e) {
            Message.error('网络错误');
          }
        },
      });
    };
  };

  return (
    <Dialog shouldUpdatePosition isFullScreen style={{ width: 1000 }} footerActions={[]} {...lastProps}>
      <Card free>
        <Card.Content>
          <Box padding={10}>
            <Form responsive fullWidth labelAlign="top" field={field}>
              <Form.Item colSpan={3} label="设备名称">
                <Input {...field.init('name')} placeholder="输入设备名称进行搜索" />
              </Form.Item>
              <Form.Item colSpan={3} label="城市">
                <Input {...field.init('city')} placeholder="输入城市进行搜索" />
              </Form.Item>
              <Form.Item colSpan={3} label="学校">
                <Input {...field.init('school')} placeholder="输入学校进行搜索" />
              </Form.Item>
              <ResponsiveGrid.Cell colSpan={3} className={styles.btns}>
                <Box spacing={8} direction="row" align="flex-end" justify="center" style={{ height: '100%' }}>
                  <Button
                    type="primary"
                    onClick={() => {
                      setPage(1);
                      setFilter(field.getValues());
                    }}
                  >
                    查询
                  </Button>
                  <Form.Reset>重置</Form.Reset>
                </Box>
              </ResponsiveGrid.Cell>
            </Form>
          </Box>
          <Divider dashed />
          <div className={styles.Main}>
            <Loading visible={loading} style={{ display: 'block' }}>
              <div className={styles.add}>
                <DatePicker.RangePicker
                  style={{ marginRight: 10 }}
                  value={dateRange}
                  onChange={(v: Moment[]) => {
                    setDateRange(v);
                  }}
                />
                <Button
                  type="primary"
                  disabled={!selectedIds.length || !dateRange || !dateRange[0] || !dateRange[1]}
                  onClick={onCast(false)}
                >
                  添加投放
                </Button>
                <Button
                  type="primary"
                  disabled={!selectedIds.length || !dateRange || !dateRange[0] || !dateRange[1]}
                  onClick={onCast(true)}
                >
                  覆盖投放
                </Button>
              </div>
              <Table
                className={styles.Table}
                hasBorder={false}
                dataSource={data?.items}
                primaryKey="_id"
                rowSelection={{
                  selectedRowKeys: selectedIds,
                  columnProps: () => ({ lock: 'left' }),
                  onChange: (ids) => {
                    setSelectedIds(ids);
                  },
                }}
                sort={{ [sort.field]: sort.order }}
                onSort={(field, order) => {
                  setPage(1);
                  setSort({ field, order });
                }}
              >
                <Table.Column title="名称" dataIndex="name" sortable />
                <Table.Column title="覆盖人数" dataIndex="coverage" align="center" sortable />
                <Table.Column
                  title="现场图片"
                  dataIndex="imgUrls"
                  align="center"
                  cell={(v: string[]) => v && v[0] && <img className={styles.img} src={v[0]} />}
                />
                <Table.Column
                  title="所在城市"
                  dataIndex="city"
                  align="center"
                  cell={(v: string) => v || '北京'}
                  sortable
                />
                <Table.Column title="所在学校" dataIndex="school" sortable />
              </Table>
              <Box margin={[15, 0, 0, 0]} direction="row" align="center" justify="space-between">
                <div className={styles.total}>共 {data?.total} 个设备</div>
                <Pagination current={page} pageSize={limit} total={data?.total} onChange={(cur) => setPage(cur)} />
              </Box>
            </Loading>
          </div>
        </Card.Content>
      </Card>
    </Dialog>
  );
};

export default DialogScreen;
